package dashboard.cli;

import java.util.Date;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
/**
 * 要实现的效果（在这里参数与命令没有任何特殊意义，只是为了表示如何完成相应的功能：
	usage: gmkdir [-p][-v/--verbose][--block-size][-h/--help] DirectoryName
	 --block-size     use SIZE-byte blocks
	 -O <file>         search for buildfile towards the root of the filesystem and use it
	 -p                    no error if existing, make parent directories as needed.
	 -v,--verbose    explain what is being done.
	 -h,--help          print help for the command.
	 
	参数说明与使用场景：
	--block-size：使用场景为：gmkdir --block-size=10 testmkdir
	-O <file>	   使用场景为：gmkdir  -O test.txt testmkdir
	-p           使用场景为：gmkdir  -p testmkdir
	-v,--verbose 使用场景为：gmkdir  -v testmkdir或gmkdir  --verbose testmkdir
	-h,--help	   使用场景为：gmkdir  -h
	 
	综合使用场景为：
	gmkdir  -h --可以查看该命令的帮助信息；
	gmkdir  -v testmkdir 或 gmkdir testmkdir  -v
	gmkdir  -v -p testmkdir/test1/test2/test3 或 gmkdir testmkdir/test1/test2/test3 -v -p
	gmkdir  -O test.txt testmkdir -v  或 gmkdir testmkdir   -O test.txt -v 
	gmkdir --block-size=10 testmkdir -v 或 gmkdir testmkdir -v --block-size=10
	gmkdir --block-size=10 testmkdir/test1/test2/test3 -p
 * @author zhaoxiang
 *
 */
@SuppressWarnings("deprecation")
public class CommandParser {
    /**
     * @param args
     * @throws InterruptedException 
     */
	public static void main(String[] args) throws InterruptedException {
    	System.err.println("-----------------commandLineParse_1-----------------");
    	commandLineParse_1(args);
    	Thread.sleep(500);
    	System.err.println("-----------------commandLineParse_2-----------------");
    	commandLineParse_2();
 
    }
	
	
    @SuppressWarnings({ "static-access" })
	public static void commandLineParse_1(String args[]){
//    	String args={};
        Options opt = new Options();
        opt.addOption("p", false, "no error if existing, " +
                "make parent directories as needed.");
        opt.addOption("v", "verbose", false, "explain what is being done.");
        opt.addOption(OptionBuilder.withArgName("file")
                .hasArg()
                .withDescription("search for buildfile towards the root of the filesystem and use it")
                .create("O"));
        opt.addOption(OptionBuilder.withLongOpt("block-size")
                .withDescription("use SIZE-byte blocks")
                .withValueSeparator('=')
                .hasArg()
                .create() );
        opt.addOption("h", "help",  false, "print help for the command.");
        
        String formatstr = "gmkdir [-p][-v/--verbose][--block-size][-h/--help] DirectoryName";
        
        HelpFormatter formatter = new HelpFormatter();
        CommandLineParser parser = new PosixParser();
        CommandLine cl = null;
        try {
            // 处理Options和参数
            cl = parser.parse( opt, args );
        } catch (ParseException e) {
            formatter.printHelp( formatstr, opt ); // 如果发生异常，则打印出帮助信息
        }
        // 如果包含有-h或--help，则打印出帮助信息
        if (cl.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp(formatstr, "", opt, "");
            return;
        }
        // 判断是否有-p参数
        if (cl.hasOption("p")) {
            System.out.println("has p");
        }
        // 判断是否有-O参数
        if (cl.hasOption("O")) {
        	System.out.println("-O = "+cl.getOptionValue("O", null));
        }
         // 判断是否有-v或--verbose参数
        if (cl.hasOption("v")) {
            System.out.println("has v");
        }
        // 获取参数值，这里主要是DirectoryName
        String[] str = cl.getArgs();
        int length = str.length;
        System.out.println("length="+length);
        System.out.println("Str[0]="+str[0]);
        //判断是否含有block-size参数
        if( cl.hasOption( "block-size" ) ) {
            // print the value of block-size
            System.out.println("block-size=" + cl.getOptionValue("block-size"));
        }
    }
    
    
    @SuppressWarnings({ "static-access" })
	public static void commandLineParse_2(){
    	String[] args = new String[]{"-t", "rensanning", "-f", "c:/aa.txt", "-b", "-s10", "-Dkey1=value1", "-Dkey2=value2" };

    	try {
    		// create Options object
    		Options options = new Options();
    		options.addOption(new Option("t", "text", true, "use given information(String)"));
    		options.addOption(new Option("b", false, "display current time(boolean)"));
    		options.addOption(new Option("s", "size", true, "use given size(Integer)"));
    		options.addOption(new Option("f", "file", true, "use given file(File)"));

    		Option property = OptionBuilder.withArgName("property=value")
    				.hasArgs(2)
    				.withValueSeparator()
    				.withDescription("use value for given property(property=value)")
    				.create("D");
    		property.setRequired(true);
    		options.addOption(property);

    		// print usage
    		HelpFormatter formatter = new HelpFormatter();
    		formatter.printHelp( "AntOptsCommonsCLI", options );
    		System.out.println();

    		// create the command line parser
			CommandLineParser parser = new PosixParser();
    		CommandLine cmd = parser.parse(options, args);

    		// check the options have been set correctly
    		System.out.println(cmd.getOptionValue("t"));
    		System.out.println(cmd.getOptionValue("f"));
    		if (cmd.hasOption("b")) {
    			System.out.println(new Date());
    		}
    		System.out.println(cmd.getOptionValue( "s" ));
    		System.out.println(cmd.getOptionProperties("D").getProperty("key1") );
    		System.out.println(cmd.getOptionProperties("D").getProperty("key2") );
    		
    	} catch (Exception ex) {
    		System.out.println( "Unexpected exception:" + ex.getMessage() );
    	}
    }
    
}

